package com.party.admin.web.controller.refund;

import com.party.admin.biz.refund.MessageOrderBizService;
import com.party.admin.biz.refund.RefundBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.core.model.order.PaymentWay;
import com.party.core.model.order.RefundPlan;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportRefundService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IRefundPlanService;
import com.party.pay.model.refund.AliPayRefundResponse;
import com.party.pay.model.refund.WechatPayRefundResponse;
import com.party.pay.service.refund.RefundOrderBizService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 此类描述的是：退款控制层
 *
 * @author: Administrator
 * @version: 2017年2月4日 下午6:25:48
 */

@Controller
@RequestMapping(value = "/refund/")
public class RefundController {

    @Autowired
    private RefundBizService refundBizService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    RefundOrderBizService refundOrderBizService;

    @Autowired
    MessageOrderBizService messageOrderBizService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private ISupportRefundService supportRefundService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IRefundPlanService refundPlanService;

    protected static Logger logger = LoggerFactory.getLogger(RefundController.class);

    @ResponseBody
    @RequestMapping("refund")
    public AjaxResult refund(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return new AjaxResult(false, "订单号不能为空");
        }
        try {
            OrderForm orderForm = orderFormService.get(orderId);
            Object responseData = refundBizService.refund(orderId, null);
            if (responseData != null) {
                if (orderForm.getPaymentWay().equals(PaymentWay.ALI_PAY.getCode())) {
                    AliPayRefundResponse response = (AliPayRefundResponse) responseData;
                    // 状态码等于10000表示成功
                    if (response.getCode().equals(Constant.ALI_SUCCESS_CODE)) {
                        return orderRefundCallback(orderId, response, PaymentWay.ALI_PAY.getCode());
                    } else {
                        logger.error("{}退款异常,异常信息{}", orderId, response.getSubMsg());
                        return new AjaxResult(false, response.getSubMsg());
                    }
                } else if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                    WechatPayRefundResponse response = (WechatPayRefundResponse) responseData;
                    // 退款成功
                    if (Constant.WECHAT_SUCCESS.equals(response.getReturnCode()) && Constant.WECHAT_SUCCESS.equals(response.getResultCode())) {
                        return orderRefundCallback(orderId, response, PaymentWay.WECHAT_PAY.getCode());
                    } else {
                        logger.error("{}退款异常, 错误描叙", orderId, response.getErrCodeDes());
                        return new AjaxResult(false, response.getErrCodeDes());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 订单退款回调
     *
     * @param orderId
     * @param refundResponse
     * @param paymentWay
     * @return
     */
    public AjaxResult orderRefundCallback(String orderId, Object refundResponse, Integer paymentWay) {
        OrderForm orderForm = orderFormService.get(orderId);
        if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
            WechatPayRefundResponse response = null;
            if (orderForm.getPaymentWay().equals(PaymentWay.WECHAT_PAY.getCode())) {
                response = (WechatPayRefundResponse) refundResponse;
            }
            if (StringUtils.isNotEmpty(orderForm.getGoodsId()) && response != null) {
                try {
                    Support support = supportService.findByOrderId(orderId);
                    supportRefundService.refund(support, response);
                } catch (Exception e) {
                    logger.error("处理退款众筹支持业务出错{}", e);
                    return new AjaxResult(false, "退款失败");
                }
            }
        } else {
            try {
                refundOrderBizService.updateRefundBusiness(orderId, refundResponse, paymentWay, null);
            } catch (Exception e) {
                logger.error("处理退款业务出错{}", e);
                return new AjaxResult(false, "退款失败");
            }
            try {
                messageOrderBizService.refundSend(orderId);
            } catch (Exception e) {
                logger.error("退款消息推送异常{}", e);
                return new AjaxResult(false, "退款失败");
            }
        }
        return new AjaxResult(true, "退款成功");
    }

    /**
    * @Author hzq
    * @Description //退款计划列表
    * @Date 17:44 2019/6/5
    * @param refundPlan
    * @param page
    * @param input
    * @return
    **/
    @RequestMapping("list")
    public ModelAndView list(RefundPlan refundPlan, Page page, CommonInput input) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("refund/refundList");
        Map<String, Object> params = CommonInput.appendParams(input);
        List<RefundPlan> refundPlanList = refundPlanService.webListPage(refundPlan, page, params);
        for (RefundPlan plan : refundPlanList) {
            if (Constant.SUPPORT.equals(plan.getType())) {
                Support support = supportService.get(plan.getGoalId());
                Activity activity = activityService.findByProjectId(support.getProjectId());
                plan.setActivityId(activity.getId());
                plan.setProjectId(support.getProjectId());
            } else if (Constant.PROJECT.equals(plan.getType())) {
                Activity activity = activityService.findByProjectId(plan.getGoalId());
                plan.setActivityId(activity.getId());
                plan.setProjectId(plan.getGoalId());
            }
        }
        mv.addObject("page", page);
        mv.addObject("refundPlanList", refundPlanList);
        mv.addObject("refundPlan", refundPlan);
        mv.addObject("input", input);
        return mv;
    }

    /**
     * @param goalId
     * @return
     * @Author hzq
     * @Description //退款计划详情
     * @Date 17:26 2019/5/17
     **/
    @RequestMapping(value = "refundPlan")
    public ModelAndView refundPlan(String goalId) {
        ModelAndView mv = new ModelAndView("refund/refundPlan");
        if (com.party.common.utils.StringUtils.isBlank(goalId)) {
            return mv;
        }
        RefundPlan refundPlan = refundPlanService.getByGoalId(goalId);
        Integer refundFailure = 0;
        Integer refundSuccess = 0;
        Integer refundTotal = 0;
        try {
            Support support = supportService.get(goalId);
            if (null == support) {
                Support support1 = new Support();
                support1.setProjectId(goalId);
                support1.setPayStatus(Constant.SUPPORT_PAY_STATUS_UNPAID);//待支付的状态
                //本次退款失败人数
                refundFailure = supportService.refundAllFailCount(goalId);
                //本次提交退款总人数，除了待支付的和退款成功的,都查出来
                List<Support> supportList = supportService.refundSubmitCount(support1);
                refundTotal = supportList.size();
                support1.setPayStatus(Constant.SUPPORT_PAY_STATUS_REFUND);
                //本次退款成功人数
                List<Support> supportList1 = supportService.refundSubmitCount(support1);
                refundSuccess = supportList1.size();
            } else {
                if (Constant.SUPPORT_PAY_STATUS_REFUND.equals(support.getPayStatus())) {
                    refundSuccess = 1;
                }
                if (Constant.SUPPORT_PAY_STATUS_FAIL.equals(support.getPayStatus())) {
                    refundFailure = 1;
                }
                refundTotal = 1;
            }
        } catch (Exception e) {
            logger.error("退款计划详情", e.getMessage());
        }
        mv.addObject("refundPlan", refundPlan);
        mv.addObject("refundFailure", refundFailure);
        mv.addObject("refundSuccess", refundSuccess);
        mv.addObject("refundTotal", refundTotal);
        return mv;
    }
}